package main

import (
	"ai-gateway/common"
	"ai-gateway/config"
	_ "ai-gateway/config"
	"ai-gateway/db"
	"ai-gateway/proto"
	"context"
	"fmt"
	"net"

	"google.golang.org/grpc"
)

type AuthServer struct {
	proto.UnimplementedAuthServiceServer
}

func (s *AuthServer) CheckPermission(ctx context.Context, req *proto.AIRequest) (*proto.AuthResponse, error) {
	//验证业务系统是否有调用权限-查数据库api_keys表
	var apiKey string
	err := db.DB.Get(&apiKey, "SELECT api_key FROM api_keys WHERE business_system = ?", req.BusinessSystem)
	allowed := err == nil
	fmt.Println("hello 2")
	// 记录审计日志
	_, err = db.DB.Exec(`
        INSERT INTO access_audit (business_system, caller, request_content)
        VALUES (?, ?, ?)
    `, req.BusinessSystem, "system", req.Prompt)
	if err != nil {
		common.Logger.Warn().Err(err).Msg("审计日志记录失败")
	}
	common.Logger.Info().
		Str("business_system", req.BusinessSystem).
		Bool("allowed", allowed).
		Msg("权限校验结果")
	return &proto.AuthResponse{Allowed: allowed, ApiKey: apiKey}, nil
}

func main() {
	common.InitLogger("auth-service")
	if err := db.InitDB(); err != nil {
		common.Logger.Fatal().Err(err).Msg("数据库初始化失败")
	}

	lis, err := net.Listen("tcp", fmt.Sprintf("%s%d", ":", config.Config.AuthServicePort))
	if err != nil {
		common.Logger.Fatal().Err(err).Msg("监听端口失败")
	}

	s := grpc.NewServer()
	proto.RegisterAuthServiceServer(s, &AuthServer{})
	common.Logger.Info().Msg("Auth Service 启动: :8084")

	if err := s.Serve(lis); err != nil {
		common.Logger.Fatal().Err(err).Msg("服务启动失败")
	}
}
